﻿using clab.Helper;
using clab.Service;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace clab
{
    public partial class Login : BasePage
    {
        public IReportService _reportService { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            IP.Text = GetIP();
        }


        protected void Submit_Logins_Click(object sender, EventArgs e)
        {
            if (uname.Text == "")
            {
                Response.Write("<script>alert('请输入您的姓名!')</script>");
                return;
            }
            if (bgnumber.Text == "")
            {
                Response.Write("<script>alert('报告编号!')</script>");
                return;
            }
            if (yz.Text == "")
            {
                Response.Write("<script>alert('请输入验证码!')</script>");
                return;
            }
            if (String.Compare(Request.Cookies["yzmcode"].Value, yz.Text, true) != 0)
            {
                Response.Write("<script>alert('验证码错误!')</script>");
                return;
            }

            var result = _reportService.GetByLabYearIdUserName(labyear.Text, bgnumber.Text, uname.Text);
            if (result == null)
            {
                Response.Write("<script> alert('暫未找到相關信息,請確認輸入正確?');</script> ");
                // Response.Redirect("http://c.laboratory.hk/");
                return;
            }
            Session["username"] = uname.Text;
            Session["bgnumber"] = bgnumber.Text;
            Session["labyear"] = labyear.Text;
            Session["phone"] = result.tel;
            if (string.IsNullOrWhiteSpace(result.tel))
            {
                Response.Write("<script>alert('手机号码检测为空，请补全手机号码后获取验证码！');</script>");
                Response.Redirect("tel.aspx");
                return;
            }
            //已发送验证码
            if (!string.IsNullOrWhiteSpace(result.khyzm))
            {
                Response.Write("<script> alert('驗證碼已經發送！');</script> ");
                Response.Redirect("telverification.aspx");
                return;
            }

            //发送短信
            sendSMSCode(result.tel, uname.Text);
            Response.Redirect("telverification.aspx");
        }
        /// <summary>
        /// 新短信验证发送  创蓝 modify by zty on 20190221
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="name"></param>
        public void sendSMSCode(string phone, string name)
        {
            string code = RandomNumHelper.getRandomNum(6);//6位随机数字
            Session["code"] = code;
            var msgSend = MsgHelper.SendSMSCode(phone, name, code);
            if (msgSend.Status)
            {
                string number = bgnumber.Text;
                _reportService.UpdateVerifyCode(number, name, code);
                JSHelper.ShowAlert(this, GetType(), "驗證碼已經發送！");
            }
            else
            {
                JSHelper.ShowAlert(this, GetType(), msgSend.Msg + ", 驗證碼发送失败，请联系管理员！！");
            }
        }

        public static string GetIP()
        {
            //如果客户端使用了代理服务器，则利用HTTP_X_FORWARDED_FOR找到客户端IP地址
            string userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null ? ""
                : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
            //否则直接读取REMOTE_ADDR获取客户端IP地址
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            //前两者均失败，则利用Request.UserHostAddress属性获取IP地址，但此时无法确定该IP是客户端IP还是代理IP
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.UserHostAddress;
            }
            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
            {
                return userHostAddress;
            }
            return "127.0.0.1";
        }
        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }
}